package com.itheima.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineUtils {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 该方法就是一个异步的方法，调用该方法的时候回单独开启一个线程 去执行该方法。
     * @param movement
     */
    @Async
    public void saveTimeLine(Movement movement) {
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3. 遍历该用户的所有好友,往时间线表插入数据
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (Friend friend : friendList) {
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(movement.getId());
            timeLine.setUserId(friend.getUserId());
            timeLine.setFriendId(friend.getFriendId());
            timeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(timeLine);
        }
    }
}
